package com.nothing.thread.hashmap;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.FileUtils;

import java.io.*;

/**
 * @author haining
 */
public class HashMapTest {

    public static void main(String[] args) throws IOException {
        createEnterpriseKeyCerFile();
        FileUtils.openInputStream(new File("/Users/haining/myjob/war/北京道口贷科技有限公司911101083182033348_20230302000001_keyStore.p12"));
    }

    private static void createEnterpriseKeyCerFile() throws IOException {
        String timestamp = "20230302000001";
        String underline = "_";
        String nameAlias = "北京道口贷科技有限公司911101083182033348";
        //住所
        String address = "北京市海淀区花园东路金澳国际大厦10层";
        //名字与姓氏
        String cn = "北京道口贷科技有限公司@911101083182033348";
        String fileLocalDir = "/Users/haining/myjob/war/";
        String keyStoreCerPath = fileLocalDir + nameAlias + DkyConstants.secretKeyFileType;
        //路径：fileLocalDir/企业ID_yymmddhhmmss_keyStore.p12
        String keyStoreFilePath = fileLocalDir + nameAlias + underline + timestamp + underline + DkdConstants.KEYSTORE_FILE_NAME;
        //生成自签名证书到密钥库语句
        String addkeyCommand = String.format(DkdConstants.ADD_KEY_COMMAND, nameAlias, keyStoreFilePath, DkdConstants.KEYSTORE_VALIDITY_DAY, cn, nameAlias, "", address, "", "CN", DkdConstants.KEYSTORE_PASSWORD);
        execCommand(addkeyCommand);
        File keyStoreFile = new File(keyStoreFilePath);
        if (keyStoreFile.length() == 0) {
            throw new RuntimeException("ResultEnum.E1410006.getResMsg() + keyStoreFilePath");
        }
        //给密钥库生成myca用于公钥的签发
        String addMyCAKeyCommand = String.format(DkdConstants.MY_CA_ADD_KEY_COMMAND, DkdConstants.MY_CA_ALIAS, keyStoreFilePath, DkdConstants.KEYSTORE_VALIDITY_DAY, DkdConstants.KEYSTORE_PASSWORD);
        execCommand(addMyCAKeyCommand);
        //生成certificate request的数据-要想让CA为我们颁发证书，首先我们要向 CA 提交申请，提交申请的时候需要提交一份称为certificate request的数据
        String csrFilePath = fileLocalDir + nameAlias + DkyConstants.SECRETKEY_CERTREQ_FILETYPE;
        String certReqCommand = String.format(DkdConstants.CREATE_CERTREQ_KEYSTORE_COMMAND, nameAlias, csrFilePath, keyStoreFilePath, DkdConstants.KEYSTORE_PASSWORD);
        execCommand(certReqCommand);
        File csrFile = new File(csrFilePath);
        if (csrFile.length() == 0) {
            throw new RuntimeException("ResultEnum.E1410009.getResMsg()");
        }
        //使用私有的MyCA来给Java颁发证书后的文件路径
        String signCertificateAfterFilePath = fileLocalDir + nameAlias + "-signAfter" + DkyConstants.secretKeyFileType;
        String gencertCommand = String.format(DkdConstants.GENCERT_KEYSTORE_COMMAND, DkdConstants.MY_CA_ALIAS, csrFilePath, signCertificateAfterFilePath, keyStoreFilePath, DkdConstants.KEYSTORE_PASSWORD, DkdConstants.KEYSTORE_VALIDITY_DAY);
        execCommand(gencertCommand);
        File signAfterFile = new File(signCertificateAfterFilePath);
        if (signAfterFile.length() == 0) {
            throw new RuntimeException("ResultEnum.E1410010.getResMsg()");
        }
        //将MyCA来给Java颁发证书导入密钥库
        String importKeyStoreCommand = String.format(DkdConstants.IMPORT_KEYSTORE_COMMAND, nameAlias, signCertificateAfterFilePath, keyStoreFilePath, DkdConstants.KEYSTORE_PASSWORD);
        execCommand(importKeyStoreCommand);
        String exportCommand = String.format(DkdConstants.EXPORT_GENERATE_KEYSTORE_COMMAND, keyStoreFilePath, nameAlias, keyStoreCerPath, DkdConstants.KEYSTORE_PASSWORD);
        execCommand(exportCommand);
        //找到生成的企业cer密钥文件
        File file = new File(keyStoreCerPath);
        if (file.length() == 0) {
            throw new RuntimeException("sdsds");
        }

        InputStream in = null;
        InputStream keyStoreIn = null;
        try {
            in = new FileInputStream(file);
            keyStoreIn = new FileInputStream(keyStoreFile);
            //计算下文件流MD5值
            String cerMD5 = DigestUtils.md5Hex(in);
            String keyStoreMD5 = DigestUtils.md5Hex(keyStoreIn);
            //分割创建文件夹
            String newCerFileFolderPath = fileLocalDir + cerMD5.substring(0, 2) + File.separator + cerMD5.substring(2, 4) + File.separator;
            String newKeyStoreFileFolderPath = fileLocalDir + keyStoreMD5.substring(0, 2) + File.separator + keyStoreMD5.substring(2, 4) + File.separator;
            //文件名称
            String newCerFileName = cerMD5 + DkyConstants.secretKeyFileType;
            String newKeyStoreFileName = keyStoreMD5 + underline + 42 + DkyConstants.KEY_STORE_SUFFIX;
            //文件完整路劲
            String newCerFilePath = newCerFileFolderPath + newCerFileName;
            String newKeyStoreFilePath = newKeyStoreFileFolderPath + newKeyStoreFileName;
            //复制到md5值的文件夹下
            FileUtil.copyFileTo(keyStoreCerPath, newCerFileFolderPath);
            FileUtil.copyFileTo(keyStoreFilePath, newKeyStoreFileFolderPath);
            //重命名
            FileUtil.renameFile(newCerFileFolderPath, nameAlias + DkyConstants.secretKeyFileType, newCerFileName);
            FileUtil.renameFile(newKeyStoreFileFolderPath, nameAlias + underline + timestamp + underline + DkdConstants.KEYSTORE_FILE_NAME, newKeyStoreFileName);
        } catch (FileNotFoundException e) {
            throw e;
        } catch (IOException e) {
            throw e;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                in.close();
            }
            if (keyStoreIn != null) {
                keyStoreIn.close();
            }
        }
    }

    public static void execCommand(String arstringCommand) {
        try {
            Process exec = Runtime.getRuntime().exec(arstringCommand);
            printMessage(exec.getErrorStream());
            InputStream inputStream = exec.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            StringBuilder sb = new StringBuilder();
            String line = null;
            try {
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                System.out.println("\n\n=====sb = " + sb);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void printMessage(final InputStream input) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Reader reader = new InputStreamReader(input);
                BufferedReader bf = new BufferedReader(reader);
                String line = null;
                StringBuilder sb = new StringBuilder();
                try {
                    while ((line = bf.readLine()) != null) {
                        System.out.println(line);
                        sb.append(line);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    System.out.println("密钥生成输出信息" + sb.toString());
                }
            }

        }).start();

    }
}
